package net.sxnic.ugr.group.action;

import net.sxnic.ugr.UgrActionSupport;
import net.sxnic.ugr.group.Group;
import net.sxnic.ugr.group.GroupManager;
import net.sxnic.ugr.role.Role;
import net.sxnic.ugr.role.util.RoleUtils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


@SuppressWarnings("serial")
public class Save extends UgrActionSupport {
	
	private static Logger logger = LoggerFactory.getLogger(Save.class);

    private Group group;

    @Autowired
    private GroupManager groupManager;
    
    /**
	 * 角色
	 */
	private String role;
	
	private String rolesHtml;
	
	 

	public void prepare() throws Exception {
		if (StringUtils.isNotBlank(id))
			group = groupManager.get(id);
    }

    public String execute() throws Exception {
		try {						
			 checkRoles(Role.SYSTEM_ADMIN);
		
			 if (StringUtils.isBlank(group.getId()))
					groupManager.save(group);
		     
		      // 角色
		  		if (StringUtils.isBlank(role)) {
		  			group.getRoles().clear();
		  			 
		  		} else {
		  			 
		  			String[] roles = StringUtils.split(role, ",");
		  			group.getRoles().clear();
		  			groupManager.update(group);
		  			Role r = null;
		  			for (String rr : roles) {
		  				r = authorizationManager.getRole(rr.trim());
		  				logger.debug("role id :" + r.getId() + " , group id :"
		  						+ group.getId());
		
		  				group.getRoles().add(r);  			 
		  			}			 
		  		} 
		  	

			    rolesHtml = RoleUtils.createCheckboxHtml(group.getRoles(),
						authorizationManager.getRoles(), "role");
				

				if (StringUtils.isBlank(group.getId()))
					groupManager.save(group);
				else
					groupManager.update(group);

		     msg = "saveSuccess";
		
		     // 保存成功信息并转向
//		     addActionMessage(getText("group.saveSuccess", new String[] { group
//		             .getName() }));		 
			
		} catch (Exception e) {
			e.printStackTrace();
		}
   
        return SUCCESS;
    }
  
    /**
     * @return the group
     */
    public Group getGroup() {
        return group;
    }

    /**
     * @param group the group to set
     */
    public void setGroup(Group group) {
        this.group = group;
    }
    
    public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public String getRolesHtml() {
		return rolesHtml;
	}

	public void setRolesHtml(String rolesHtml) {
		this.rolesHtml = rolesHtml;
	}
	
}
